package com.bdth.controller;

import com.bdth.model.EnclosureConfig;
import com.bdth.model.PageModel;
import com.bdth.model.PointLatLng;
import com.bdth.model.User;
import com.bdth.service.IEnclosureService;
import com.bdth.service.IHisGpsService;
import com.bdth.utils.*;
import com.bdth.utils.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/hisGps")
public class HisGpsController extends BaseController {

	@Autowired
	private IHisGpsService hisGpsService;

	@Autowired
	private IEnclosureService enclosureService;

	protected static final Logger logger = LoggerFactory.getLogger(HisGpsController.class);


	/**
	 * 地图页面
	 *
	 * @return
	 */
	@GetMapping(value = "/map")
	public ModelAndView getMapPage(Model model) {

		return forword("/hisroute/baidu");
	}

	/**
	 * 地图页面
	 *
	 * @return
	 */
	@GetMapping(value = "/google")
	public ModelAndView getGoogleMapPage(Model model) {

		return forword("/hisroute/google");
	}

	/**
	 * 查看marker页面
	 *
	 * @return
	 */
	@RequestMapping("/viewMarker")
	public ModelAndView viewMarker(int id, String enclosureType, String strRoutePoints, HttpServletRequest request, HttpServletResponse response) throws Exception {
		double radius = 0;
		Map<String, Object> context = getRootMap();
		EnclosureConfig e = new EnclosureConfig();
		EnclosureConfig enclosureConfig = enclosureService.queryById(id);
		if (enclosureConfig != null) {
			e = enclosureConfig;
			if (Constants.MAP_BAIDU.equals(enclosureConfig.getMaptype())) {
				String points = "";
				String[] p = enclosureConfig.getPoints().split(";");
				for (int i = 0; i < p.length; i++) {

					PointLatLng pl = BaiduMapFixService.bd_decrypt(Double.valueOf(p[i].split(",")[1]), Double.valueOf(p[i].split(",")[0]));
					points += pl.getLng() + "," + pl.getLat() + ";";
				}
				enclosureConfig.setPoints(points.substring(0, points.length() - 1));
				PointLatLng pl1 = BaiduMapFixService.bd_decrypt(enclosureConfig.getCenterLat(), enclosureConfig.getCenterLng());
				enclosureConfig.setCenterLat(pl1.getLat());
				enclosureConfig.setCenterLng(pl1.getLng());
			}
		}
		if (!StringUtil.isEmptyWithNullStr(request.getParameter("radius"))) {
			radius = Double.valueOf(request.getParameter("radius"));
		}
		if (id == 0) {
			e.setRadius((new Double(radius)).intValue());
			e.setPoints(strRoutePoints);
			e.setEnclosureType(EnclosureConfig.MARKER);
		}
		context.put("enclosure", e);
		context.put("id", id);
		context.put("strRoutePoints", strRoutePoints);
		return forword("/hisroute/editMarker", context);

	}

	@RequestMapping("/viewArea")
	public ModelAndView viewArea(int id, String enclosureType, String strRoutePoints, HttpServletRequest request, HttpServletResponse response) throws Exception {

		double radius = 0;
		Map<String, Object> context = getRootMap();
		EnclosureConfig e = new EnclosureConfig();
		EnclosureConfig enclosureConfig = enclosureService.queryById(id);
		if (enclosureConfig != null) {
			e = enclosureConfig;
		/*	Department department = departmentService.queryById(e.getDepId());
		    if (department != null) {
				context.put("depName", department.getDepName());
			}*/
			context.put("startTime1", DateUtil.getPlusTime(e.getStartDate()));
			context.put("endTime1", DateUtil.getPlusTime(e.getEndDate()));
			if (Constants.MAP_BAIDU.equals(enclosureConfig.getMaptype())) {
				String points = "";
				String[] p = enclosureConfig.getPoints().split(";");
				for (int i = 0; i < p.length; i++) {

					PointLatLng pl = BaiduMapFixService.bd_decrypt(Double.valueOf(p[i].split(",")[1]), Double.valueOf(p[i].split(",")[0]));
					points += pl.getLng() + "," + pl.getLat() + ";";
				}
				enclosureConfig.setPoints(points.substring(0, points.length() - 1));
				PointLatLng pl1 = BaiduMapFixService.bd_decrypt(enclosureConfig.getCenterLat(), enclosureConfig.getCenterLng());
				enclosureConfig.setCenterLat(pl1.getLat());
				enclosureConfig.setCenterLng(pl1.getLng());
			}
		}
		if (!StringUtil.isEmptyWithNullStr(request.getParameter("radius"))) {
			radius = Double.valueOf(request.getParameter("radius"));
		}
		if (!StringUtil.isEmptyWithNullStr(enclosureType)) {
			String ecType = "";
			if ("circle".equals(enclosureType))
				ecType = EnclosureConfig.CIRCLE;
			else if ("rect".equals(enclosureType))
				ecType = EnclosureConfig.RECT;
			else if ("polygon".equals(enclosureType))
				ecType = EnclosureConfig.POLYGON;
			e.setEnclosureType(ecType);
		} else
			enclosureType = e.getEnclosureType();

		if (id == 0) {
			e.setRadius((new Double(radius)).intValue());
			e.setPoints(strRoutePoints);
			//e.setDepId(0);
		}

		context.put("enclosure", e);
		context.put("id", id);
		context.put("strRoutePoints", strRoutePoints);
		return forword("/hisroute/editArea", context);


	}


	/**
	 * json 列表页面
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/dataList")
	public void dataList(PageModel pageModel, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		List dataList = getDataList(pageModel, request, true);

		for (Object obj : dataList) {
			try {
				Map r = (Map) obj;
				double longitude = Double.parseDouble("" + r.get("longitude"));
				double latitude = Double.parseDouble("" + r.get("latitude"));
				r.put("orgLatitude", latitude);
				r.put("orgLongitude", longitude);
				PointLatLng pt = MapFixService.fix(latitude, longitude,
						Constants.MAP_GOOGLE);
				r.put("longitude", pt.getLng());
				r.put("latitude", pt.getLat());

				int direction = (Integer) r.get("direction");
				String directionDescr = this.getDirectionDescr(direction);
				r.put("directionDescr", directionDescr);

				int status1 = (Integer) r.get("status");
				String strStatus = Integer.toBinaryString(status1);
				strStatus = StringUtil.leftPad(strStatus, 32, '0');
				strStatus = getStatusDescr(strStatus);
				r.put("status", strStatus);
				int alarmState = (Integer) r.get("alarmState");
				String alarmStateDescr = getAlarmDescr(alarmState);
				r.put("alarmStateDescr", alarmStateDescr);
			} catch (Exception ex) {
				logger.error(ex.getMessage(), ex);
			}
		}
		//获得结果集条总数
		PageInfo pageList = new PageInfo(dataList);
		//设置页面数据
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("total", pageList.getTotal());
		jsonMap.put("rows", dataList);
		HtmlUtil.writerJson(response, jsonMap);
	}

	protected String getDirectionDescr(int direction) {
		String descr = "";
		if (direction == 0) {
			descr = "正北";
		} else if (direction == 90) {
			descr = "正东";
		} else if (direction == 180) {
			descr = "正南";
		} else if (direction == 270) {
			descr = "正西";
		} else if (direction == 45) {
			descr = "东北";
		} else if (direction == 135) {
			descr = "东南";
		} else if (direction == 225) {
			descr = "西南";
		} else if (direction == 315) {
			descr = "西北";
		} else if (direction < 90) {
			descr = "东偏北" + (90 - direction) + "度";
		} else if (direction > 90 && direction < 180) {
			descr = "东偏南" + (direction - 90) + "度";
		} else if (direction > 180 && direction < 270) {
			descr = "西偏南" + (270 - direction) + "度";
		} else if (direction > 270 && direction < 360) {
			descr = "西偏北" + (direction - 270) + "度";
		}
		return descr;
	}

	protected String getStatusDescr(String status) {
		StringBuilder sb = new StringBuilder();

		if (StringUtil.isEmptyWithNullStr(status) == false) {
			char[] ch = status.toCharArray();
			if (ch.length == 32) {
				int m = 31;
				int c = ch[m - 0] - 48;
				sb.append(c == 1 ? "ACC开" : "ACC关").append(",");
				c = ch[m - 1] - 48;
				sb.append(c == 1 ? "定位" : "未定位").append(",");
				c = ch[m - 4] - 48;
				sb.append(c == 1 ? "停运" : "运营").append(",");
				c = ch[m - 10] - 48;
				sb.append(c == 1 ? "油路断开" : "油路正常").append(",");
				c = ch[m - 11] - 48;
				sb.append(c == 1 ? "电路断开" : "电路正常").append(",");
				c = ch[m - 12] - 48;
				sb.append(c == 1 ? "车门加锁" : "车门解锁").append(",");
			}
		}

		return sb.toString();
	}

	private static String[] signalDescr = new String[]{"近光灯", "远光灯", "右转向灯",
			"左转向灯", "制动", "倒档"};

	protected String getSignalDescr(int signal) {
		StringBuilder sb = new StringBuilder();
		String strStatus = Integer.toBinaryString(signal);
		strStatus = StringUtil.leftPad(strStatus, 32, '0');

		char[] ch = strStatus.toCharArray();
		for (int m = 0; m < ch.length && m < signalDescr.length; m++) {
			int c = ch[31 - m] - 48;
			if (StringUtil.isEmptyWithNullStr(signalDescr[m]) == false) {
				sb.append(signalDescr[m]).append(c == 1 ? "开" : "关").append(",");
			}
		}

		return sb.toString();
	}


	/**
	 * 报警描述
	 *
	 * @param alarmState
	 * @return
	 */
	protected String getAlarmDescr(int alarmState) {
		StringBuilder sb = new StringBuilder();
		String alarm = Integer.toBinaryString(alarmState);
		alarm = StringUtil.leftPad(alarm, 32, '0');
		if (StringUtil.isEmptyWithNullStr(alarm) == false) {
			char[] ch = alarm.toCharArray();
			for (int m = 0; m < ch.length; m++) {
				int tag = Integer.parseInt("" + ch[m]);
				if (tag == 1) {
					int alarmId = 31 - m; // 倒序，转换为部标的报警序号
				/*	BasicDataNew bd = BaseDataNewService.service.getBasicDataByCode(""
		                    + alarmId, "AlarmType");
					if (bd != null) {
						sb.append(bd.getName()).append(",");
					}*/
				}
			}
		}

		return sb.toString();
	}

	public List getDataList(PageModel pageModel, HttpServletRequest request, boolean pageFlag) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map> dataList = null;
		String hisRoute = request.getParameter("hisRoute");
		String equipName = request.getParameter("equipName");
		String simNo = request.getParameter("simNo");
		String startTime = "" + request.getParameter("startTime");
		String endTime = "" + request.getParameter("endTime");
		String minSpeed = request.getParameter("minSpeed");
		String dataListForView = request.getParameter("dataListForView");
		if (StringUtil.isEmptyWithNullStr(startTime)) {
			startTime = DateUtil.convertDateToYearMonthDay(new Date());
			endTime = DateUtil.convertDateToYearMonthDay(new Date());
		} else {
			startTime = startTime.substring(0, 10).replace("-", "");
			endTime = endTime.substring(0, 10).replace("-", "");
		}
		String today = DateUtil.getFomartDate(new Date(), "yyyyMMdd");
		if (endTime.compareTo(today) > 0)
			endTime = today;
		map.put("simNo", simNo);

		String tableName1 = "tb_HisGpsData" + startTime;
		String tableName2 = "tb_HisGpsData" + endTime;
		map.put("tableName1", tableName1);
		map.put("tableName2", tableName2);

		map.put("startTime", request.getParameter("startTime"));
		map.put("endTime", request.getParameter("endTime"));
		map.put("minSpeed", minSpeed);
		map.put("equipName", equipName);
		map.put("hisRoute", hisRoute);
		User user = SessionUtils.getUser(request);
		List<Integer> depIds = getDepIds(user.getDepId());
		map.put("depIds", depIds);
		map.put("dataListForView", dataListForView);
		if (pageFlag) {
			//紧跟着的第一个查询方法会被分页
			PageHelper.startPage(pageModel.getPage(), pageModel.getRows());
		}
		if (tableName1.equals(tableName2) == false) {
			dataList = hisGpsService.queryMapDataByMapListIn2Days(map);
		} else {
			dataList = hisGpsService.queryMapDataByMapList(map);
		}
		return dataList;
	}


	/**
	 * 导出历史数据
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/exportHisGps")
	public void exportHisGps(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			List dataList = getDataList(null, request, false);
			String equipName = request.getParameter("equipName");
			String simNo = request.getParameter("simNo");

			String separator = File.separator;
			String xlsFile = System.getProperty("csc2.root") + separator
					+ "excel" + separator
					+ "hisGpsModel.xlsx";
			String filename = "历史定位数据.xlsx";// 设置下载时客户端Excel的名称
			OutputStream ouputStream = null;
			Workbook workbook = WorkbookFactory.create(new FileInputStream(xlsFile));
			Sheet sheet = workbook.getSheetAt(0);
			Font headerFont = workbook.createFont(); // 字体
			headerFont.setFontHeightInPoints((short) 11);
			headerFont.setFontName("Arial");
			int count = 0;
			// 设置数据行

			Row row1 = sheet.getRow(0);
			Cell cell1 = row1.getCell(1);
			cell1.setCellValue(equipName);
			Cell cell2 = row1.getCell(3);
			cell2.setCellValue(simNo);
			Row row2 = sheet.getRow(1);
			Cell cell3 = row2.getCell(1);
			cell3.setCellValue(request.getParameter("startTime"));
			Cell cell4 = row2.getCell(3);
			cell4.setCellValue(request.getParameter("endTime"));
			CellStyle cellStyle = workbook.createCellStyle();

			cellStyle.setAlignment(XSSFCellStyle.ALIGN_LEFT);


			cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 水平布局：居中
			cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
			cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
			cellStyle.setBottomBorderColor(new XSSFColor(java.awt.Color.BLACK).getIndexed());
			cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
			cellStyle.setLeftBorderColor(new XSSFColor(java.awt.Color.BLACK).getIndexed());
			cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
			cellStyle.setRightBorderColor(new XSSFColor(java.awt.Color.BLACK).getIndexed());
			cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
			cellStyle.setTopBorderColor(new XSSFColor(java.awt.Color.BLACK).getIndexed());
			cellStyle.setFont(headerFont);
			cellStyle.setWrapText(true);

			int i = 0;
			for (Object obj : dataList) {
				Map r = (Map) obj;
				try {
					int direction = (Integer) r.get("direction");
					String directionDescr = this.getDirectionDescr(direction);
					Object[] data = {r.get("equipName") + "",
							r.get("simNo") + "",
							r.get("depName") + "",
							DateUtil.getPlusTime(DateUtil.getDateFromString(r.get("sendTime") + "")),
							r.get("longitude") + "",
							r.get("latitude") + "",
							r.get("velocity") + "",
							directionDescr};
					ExportExcelUtil.writeRowLine(workbook,
							sheet, cellStyle,
							headerFont,
							i + 3,
							data);
					i++;
				} catch (Exception e) {
					logger.error(e.getMessage());
					continue;
				}
			}


			filename = ExportExcelUtil.encodeFilename(filename, request);
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.addHeader("Content-Disposition", "attachment;filename=" + filename);
			ouputStream = response.getOutputStream();
			workbook.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();

		} catch (IOException e) {
			logger.error(e.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
		}

	}
}
